package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.News;
import com.example.springboot.entity.Sign;
import com.example.springboot.entity.News;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.NewsService;
import com.example.springboot.service.SignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 竞赛标签类型相关接口
 */
@RestController
@RequestMapping("/sign")
public class SignController {

    @Autowired
    SignService signService;

    @Autowired
    NewsService newsService;
    /**
     * 新增信息 post
     */
    @HoneyLogs(operation = "竞赛标签类型", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody Sign sign) {
        try {
            if (sign.getType().length() > 10 ) {//要求名字长度小于等于10
                return Result.error("竞赛标签名称过长");
            }
            sign.setAddtime(DateUtil.now()); //获取当前的时间(格式: yyyy-mm-dd HH:MM:SS) 如果是today则是yyyy-mm-dd
            signService.save(sign);//service中的函数
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {//数据库插入重复错误时报错
                return Result.error("竞赛标签重复");
            } else {
                return Result.error("系统错误");//其他报错
            }
        }
        return Result.success();
    }

    /**
     * 修改信息 put
     */
    @HoneyLogs(operation = "竞赛标签类型", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody Sign sign) {
        try {
            if (sign.getType().length() > 10 ) {//要求名字长度小于等于10
                return Result.error("竞赛标签名称过长");
            }
            signService.updateById(sign);//service中的函数
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {//数据库插入重复错误时报错
                return Result.error("竞赛标签重复");
            } else {
                return Result.error("系统错误");//其他报错
            }
        }
        return Result.success();
    }

    /**
     * 删除信息
     */
    @HoneyLogs(operation = "竞赛标签类型", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        //如果该标签被使用则不能删除
        //news中被使用的标签转化为数组
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        List<News> newsList = newsService.list(queryWrapper);
        List<String> signList = newsList.stream().map(News::getSign).distinct().collect(Collectors.toList());
        //如果标签中存在news表中则不能删除
        String id1 = signService.getById(id).getType();
        for (String s : signList) {
            if (id1.equals(s)) {
                throw new ServiceException("该标签已被使用");
            }
        }
        signService.removeById(id);
        return Result.success();
    }


    /**
     * 批量删除信息
     */
    @HoneyLogs(operation = "竞赛标签类型", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        //如果该标签被使用则不能删除（没有完善news表，暂时无法验证）
        //user中被使用的标签转化为数组
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        List<News> newsList = newsService.list(queryWrapper);
        List<String> signList = newsList.stream().map(News::getSign).distinct().collect(Collectors.toList());
        List<Sign> signList1 = signService.listByIds(ids);
        List<String> type = signList1.stream().map(Sign::getType).collect(Collectors.toList());
        //如果标签中存在user表中则不能删除
        for (String s : signList) {
            if ( type.contains(s)) {
                throw new ServiceException("有标签已被使用");
            }
        }
        signService.removeBatchByIds(ids);
        return Result.success();
    }

    /**
     * 多条件模糊查询信息
     * pageNum 当前的页码
     * pageSize 每页查询的个数
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String type
                               ) {
        QueryWrapper<Sign> queryWrapper = new QueryWrapper<Sign>().orderByDesc("id");  // 默认倒序，让最新的数据在最上面
        queryWrapper.like(StrUtil.isNotBlank(type), "type", type);
        Page<Sign> page = signService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    /**
     * 查询所有，返回单个元素列（type）
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        QueryWrapper<Sign> queryWrapper = new QueryWrapper<Sign>().orderByDesc("id");  // 默认倒序，让最新的数据在最上面
        List<Sign> facultyList = signService.list(queryWrapper);
        //select * from user order by id desc
        List<String> typeList = facultyList.stream().map(Sign::getType).collect(Collectors.toList());
        return Result.success(typeList);
    }

}
